package hw;

public class QKL {

    public static void main(String[] args) {
        System.out.println(maxSum(new int[]{100, 500, 400, 150, 500, 100}, 1000));
    }

    private static int maxSum(int[] nums, int top) {
        // 控制指针
        if (nums.length == 0) {
            return 0;
        }
        int maxSum = 0;
        int i = 0,j = 0;
        int sum = 0;
        while (i < nums.length - 1) {
            if (sum < top) {
                // 指针向后
                sum += nums[i];
                if (sum < top) {
                    maxSum = Integer.max(maxSum, sum);
                }
                i ++;
            } else if (sum == top) {
                return sum;
            } else {
                sum -= nums[j];
                j ++;
                if (sum < top) {
                    maxSum = Integer.max(maxSum, sum);
                }
            }
        }
        return maxSum;
    }

}
